package com.css.zfzx.sjcj.modules.hddcwyVolcanicSamplePoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.repository.HddcVolcanicsamplepointRepository;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.repository.entity.HddcVolcanicsamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSamplePoint.repository.HddcWyVolcanicsamplepointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSamplePoint.repository.HddcWyVolcanicsamplepointRepository;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSamplePoint.repository.entity.HddcWyVolcanicsamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSamplePoint.service.HddcWyVolcanicsamplepointService;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSamplePoint.viewobjects.HddcWyVolcanicsamplepointQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyVolcanicSamplePoint.viewobjects.HddcWyVolcanicsamplepointVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * @author zhangcong
 * @date 2020-12-02
 */
@Service
public class HddcWyVolcanicsamplepointServiceImpl implements HddcWyVolcanicsamplepointService {

	@Autowired
    private HddcWyVolcanicsamplepointRepository hddcWyVolcanicsamplepointRepository;
    @Autowired
    private HddcWyVolcanicsamplepointNativeRepository hddcWyVolcanicsamplepointNativeRepository;
    @Autowired
    private HddcVolcanicsamplepointRepository hddcVolcanicsamplepointRepository;
    @Override
    public JSONObject queryHddcWyVolcanicsamplepoints(HddcWyVolcanicsamplepointQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyVolcanicsamplepointEntity> hddcWyVolcanicsamplepointPage = this.hddcWyVolcanicsamplepointNativeRepository.queryHddcWyVolcanicsamplepoints(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyVolcanicsamplepointPage);
        return jsonObject;
    }


    @Override
    public HddcWyVolcanicsamplepointEntity getHddcWyVolcanicsamplepoint(String uuid) {
        HddcWyVolcanicsamplepointEntity hddcWyVolcanicsamplepoint = this.hddcWyVolcanicsamplepointRepository.findById(uuid).orElse(null);
         return hddcWyVolcanicsamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyVolcanicsamplepointEntity saveHddcWyVolcanicsamplepoint(HddcWyVolcanicsamplepointEntity hddcWyVolcanicsamplepoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyVolcanicsamplepoint.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyVolcanicsamplepoint.getCreateUser())){
            hddcWyVolcanicsamplepoint.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyVolcanicsamplepoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyVolcanicsamplepoint.setIsValid("1");

        HddcVolcanicsamplepointEntity hddcVolcanicsamplepointEntity=new HddcVolcanicsamplepointEntity();
        BeanUtils.copyProperties(hddcWyVolcanicsamplepoint,hddcVolcanicsamplepointEntity);
        hddcVolcanicsamplepointEntity.setExtends4(hddcWyVolcanicsamplepoint.getTown());
        hddcVolcanicsamplepointEntity.setExtends5(String.valueOf(hddcWyVolcanicsamplepoint.getLon()));
        hddcVolcanicsamplepointEntity.setExtends6(String.valueOf(hddcWyVolcanicsamplepoint.getLat()));
        this.hddcVolcanicsamplepointRepository.save(hddcVolcanicsamplepointEntity);

        this.hddcWyVolcanicsamplepointRepository.save(hddcWyVolcanicsamplepoint);
        return hddcWyVolcanicsamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyVolcanicsamplepointEntity updateHddcWyVolcanicsamplepoint(HddcWyVolcanicsamplepointEntity hddcWyVolcanicsamplepoint) {
        HddcWyVolcanicsamplepointEntity entity = hddcWyVolcanicsamplepointRepository.findById(hddcWyVolcanicsamplepoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyVolcanicsamplepoint);
        hddcWyVolcanicsamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyVolcanicsamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyVolcanicsamplepointRepository.save(hddcWyVolcanicsamplepoint);
        return hddcWyVolcanicsamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyVolcanicsamplepoints(List<String> ids) {
        List<HddcWyVolcanicsamplepointEntity> hddcWyVolcanicsamplepointList = this.hddcWyVolcanicsamplepointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWyVolcanicsamplepointList) && hddcWyVolcanicsamplepointList.size() > 0) {
            for(HddcWyVolcanicsamplepointEntity hddcWyVolcanicsamplepoint : hddcWyVolcanicsamplepointList) {
                this.hddcWyVolcanicsamplepointRepository.delete(hddcWyVolcanicsamplepoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyVolcanicsamplepoint(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyVolcanicsamplepointNativeRepository.queryHddcWyVolcanicsamplepoint(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyVolcanicsamplepointEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyVolcanicsamplepointEntity> list = hddcWyVolcanicsamplepointRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }


    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyVolcanicsamplepointEntity> hddcWyVolcanicsamplepointEntity = hddcWyVolcanicsamplepointNativeRepository.exportVolcanPoint(queryParams);
        List<HddcWyVolcanicsamplepointVO> list=new ArrayList<>();
        for (HddcWyVolcanicsamplepointEntity entity:hddcWyVolcanicsamplepointEntity) {
            HddcWyVolcanicsamplepointVO hddcWyVolcanicsamplepointVO=new HddcWyVolcanicsamplepointVO();
            BeanUtils.copyProperties(entity,hddcWyVolcanicsamplepointVO);
            list.add(hddcWyVolcanicsamplepointVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"火山采样点-点","火山采样点-点", HddcWyVolcanicsamplepointVO.class,"火山采样点-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWyVolcanicsamplepointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyVolcanicsamplepointVO.class, params);
            List<HddcWyVolcanicsamplepointVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWyVolcanicsamplepointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWyVolcanicsamplepointVO hddcWyVolcanicsamplepointVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + hddcWyVolcanicsamplepointVO.getRowNum() + "行" + hddcWyVolcanicsamplepointVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcWyVolcanicsamplepointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWyVolcanicsamplepointEntity hddcWyVolcanicsamplepointEntity = new HddcWyVolcanicsamplepointEntity();
            HddcWyVolcanicsamplepointVO hddcWyVolcanicsamplepointVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcWyVolcanicsamplepointVO, hddcWyVolcanicsamplepointEntity);
            saveHddcWyVolcanicsamplepoint(hddcWyVolcanicsamplepointEntity);
        }
    }


    @Override
    public List<HddcWyVolcanicsamplepointEntity> findAllByCreateUserAndIsValid(String userId, String isValid) {
        List<HddcWyVolcanicsamplepointEntity> list = hddcWyVolcanicsamplepointRepository.findAllByCreateUserAndIsValid(userId, isValid);
        return list;
    }


    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyVolcanicsamplepointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyVolcanicsamplepointRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyVolcanicsamplepointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyVolcanicsamplepointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyVolcanicsamplepointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyVolcanicsamplepointRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyVolcanicsamplepointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyVolcanicsamplepointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }














}
